package com.edu.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisPoolUtils {
    //连接池
    private static JedisPool jedisPool;

    static {
        try {
            Properties properties = new Properties();
            InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedisConfig.properties");
            properties.load(in);

            //获取数据，设置到JedisPoolConfig中
            JedisPoolConfig config = new JedisPoolConfig();
            //控制一个pool可分配多少个jedis实例
            config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
            //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例
            config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));

            //JedisPool jedisPool = new JedisPool(config, "127.0.0.1", 6379, 5000, "123456", 1);
            String host = properties.getProperty("host");
            int port = Integer.parseInt(properties.getProperty("port"));
            int timeout = Integer.parseInt(properties.getProperty("timeout"));

            jedisPool = new JedisPool(config,host,port,timeout);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //返回连接池
    public static Jedis getJedis() {
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }
}
